package com.system.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.business.domain.DailyTrain;
import com.system.business.domain.DailyTrainTicket;
import com.system.business.domain.TrainStation;
import com.system.business.enums.SeatTypeEnum;
import com.system.business.enums.TrainTypeEnum;
import com.system.business.req.DailyTrainTicketQueryReq;
import com.system.business.req.DailyTrainTicketSaveReq;
import com.system.business.resp.DailyTrainTicketQueryResp;
import com.system.business.service.*;
import com.system.business.mapper.DailyTrainTicketMapper;
import com.system.common.resp.PageResp;
import com.system.common.utils.SnowUtil;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
* @author Admin
* @description 针对表【daily_train_ticket(余票信息)】的数据库操作Service实现
* @createDate 2024-03-21 15:02:15
*/
@Service
public class DailyTrainTicketServiceImpl extends ServiceImpl<DailyTrainTicketMapper, DailyTrainTicket>
    implements DailyTrainTicketService{
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainSeatService.class);

    @Autowired
    private DailyTrainTicketMapper dailyTrainTicketMapper;
    @Autowired
    private TrainService trainService;
    @Autowired
    private TrainStationService trainStationService;
    @Resource
    private DailyTrainStationService dailyTrainStationService;

    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;

    @Resource
    private DailyTrainSeatService dailyTrainSeatService;

    @Resource
    private DailyTrainTicketService dailyTrainTicketService;
    @Override
    public void save(DailyTrainTicketSaveReq req) {
        DateTime now = DateTime.now();

        DailyTrainTicket dailyTrainTicket = BeanUtil.copyProperties(req, DailyTrainTicket.class);
        if (ObjectUtil.isNull(dailyTrainTicket.getId())) {
            dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainTicket.setCreateTime(now);
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.insert(dailyTrainTicket);
        } else {
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.updateById(dailyTrainTicket);
        }
    }

    @CachePut(value = "DailyTrainTicketService.queryList")
    public PageResp<DailyTrainTicketQueryResp> queryList2(DailyTrainTicketQueryReq req){
        return queryList(req);
    }

 //   @Override
    @Cacheable(value = "DailyTrainTicketService.queryList")
    @Override
    public PageResp<DailyTrainTicketQueryResp> queryList(DailyTrainTicketQueryReq req) {
        Page<DailyTrainTicket> pageCondition = new Page<>(req.getPage(), req.getSize());
        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        QueryWrapper<DailyTrainTicket> dailyTrainTicketQueryWrapper = new QueryWrapper<>();
        if (ObjUtil.isNotNull(req.getDate())) {
            dailyTrainTicketQueryWrapper.eq("date",req.getDate());
        }
        if (ObjUtil.isNotEmpty(req.getTrainCode())) {
            dailyTrainTicketQueryWrapper.eq("train_code",req.getTrainCode());
        }
        if (ObjUtil.isNotEmpty(req.getStart())) {
            dailyTrainTicketQueryWrapper.eq("start",req.getStart());
        }
        if (ObjUtil.isNotEmpty(req.getEnd())) {
            dailyTrainTicketQueryWrapper.eq("end",req.getEnd());
        }
        Page<DailyTrainTicket> pageData = dailyTrainTicketMapper.selectPage(pageCondition,dailyTrainTicketQueryWrapper);
        List<DailyTrainTicketQueryResp> list = BeanUtil.copyToList(pageData.getRecords(), DailyTrainTicketQueryResp.class);
        LOG.info("总行数：{}", pageData.getTotal());
        LOG.info("总页数：{}", pageData.getPages());
        PageResp<DailyTrainTicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageData.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    @Transactional
    @Override
    public void genDaily(DailyTrain dailyTrain, Date date, String trainCode){
        //删除某日某车次的余票信息
        QueryWrapper<DailyTrainTicket> dailyTrainTicketQueryWrapper = new QueryWrapper<>();
        dailyTrainTicketQueryWrapper.eq("train_code",trainCode);
        dailyTrainTicketQueryWrapper.eq("date",date);
        dailyTrainTicketMapper.delete(dailyTrainTicketQueryWrapper);

        //查询所有车站的信息
        QueryWrapper<TrainStation> trainStationQueryWrapper = new QueryWrapper<TrainStation>();
        trainStationQueryWrapper.eq("train_code",trainCode);
        List<TrainStation> trainStations = trainStationService.list(trainStationQueryWrapper);

        if(CollectionHelper.isEmpty(trainStations)){
            System.out.println("没有该车站的信息");
            return;
        }
        DateTime now = DateTime.now();
        for(int i=0;i<trainStations.size();i++){
            //得到出发站点
            BigDecimal sumKM = BigDecimal.ZERO;
            TrainStation trainStationStart = trainStations.get(i);
            for(int j=i+1;j<trainStations.size();j++){
                TrainStation trainStationEnd = trainStations.get(j);
                sumKM = sumKM.add(trainStationEnd.getKm());



                DailyTrainTicket dailyTrainTicket = new DailyTrainTicket();
                dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainTicket.setDate(date);
                dailyTrainTicket.setTrainCode(trainCode);
                dailyTrainTicket.setStart(trainStationStart.getName());
                dailyTrainTicket.setStartPinyin(trainStationStart.getNamePinyin());
                dailyTrainTicket.setStartTime(trainStationStart.getOutTime());
                dailyTrainTicket.setStartIndex(trainStationStart.getIndexCode());

                dailyTrainTicket.setEnd(trainStationEnd.getName());
                dailyTrainTicket.setEndPinyin(trainStationEnd.getNamePinyin());
                dailyTrainTicket.setEndTime(trainStationEnd.getInTime());
                dailyTrainTicket.setEndIndex(trainStationEnd.getIndexCode());

                int ydz = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.YDZ.getCode());
                int edz = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.EDZ.getCode());
                int rw = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.RW.getCode());
                int yw = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.YW.getCode());

                // 票价 = 里程之和 * 座位单价 * 车次类型系数
                String trainType = dailyTrain.getType();
                // 计算票价系数：TrainTypeEnum.priceRate
                BigDecimal priceRate = EnumUtil.getFieldBy(TrainTypeEnum::getPriceRate, TrainTypeEnum::getCode, trainType);
                BigDecimal ydzPrice = sumKM.multiply(SeatTypeEnum.YDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal edzPrice = sumKM.multiply(SeatTypeEnum.EDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal rwPrice = sumKM.multiply(SeatTypeEnum.RW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal ywPrice = sumKM.multiply(SeatTypeEnum.YW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);

                dailyTrainTicket.setYdz(ydz);
                dailyTrainTicket.setYdzPrice(ydzPrice);
                dailyTrainTicket.setEdz(edz);
                dailyTrainTicket.setEdzPrice(edzPrice);
                dailyTrainTicket.setRw(rw);
                dailyTrainTicket.setRwPrice(rwPrice);
                dailyTrainTicket.setYw(yw);
                dailyTrainTicket.setYwPrice(ywPrice);
                dailyTrainTicket.setCreateTime(now);
                dailyTrainTicket.setUpdateTime(now);
                dailyTrainTicketMapper.insert(dailyTrainTicket);
            }
        }

    }

    @Override
    public DailyTrainTicket selectByUnique(Date date, String trainCode, String start, String end) {
        QueryWrapper<DailyTrainTicket> dailyTrainTicketQueryWrapper = new QueryWrapper<>();
        dailyTrainTicketQueryWrapper.eq("date",date)
                        .eq("train_code",trainCode).eq("start",start)
                        .eq("end",end);
        DailyTrainTicket dailyTrainTicket = dailyTrainTicketMapper.selectOne(dailyTrainTicketQueryWrapper);
        return dailyTrainTicket;
    }

    @Override
    public void  reduceTicketNum(Date date, String trainCode, String start, String end, String seatType){
        QueryWrapper<DailyTrainTicket> dailyTrainTicketQueryWrapper = new QueryWrapper<>();
        dailyTrainTicketQueryWrapper.eq("date",date)
                .eq("train_code",trainCode).eq("start",start)
                .eq("end",end).eq("seat_type",seatType);
        DailyTrainTicket dailyTrainTicket = dailyTrainTicketMapper.selectOne(dailyTrainTicketQueryWrapper);
        if ("ydz".equals(seatType)){
            dailyTrainTicket.setYdz(dailyTrainTicket.getYdz()-1);
        }else {
            dailyTrainTicket.setEdz(dailyTrainTicket.getEdz()-1);
        }
    }
}




